<!-- src/components/authentication/LoginModal.vue -->
<template>
  <Teleport to="body">
    <Transition name="modal-fade-up">
      <div v-if="model" class="login-modal-overlay" @click.self="close">
        <div class="login-modal" @click.stop>
          <header class="modal-header">
            <div class="left" @click="close">
              <Icon name="guanbi" size="24" color="#ccc" />
            </div>
            <span class="modal-title" @click="goregister">注册账号</span>
          </header>
          <h2 class="title">登录后即可展示自己</h2>
          <form @submit.prevent="handleSubmit" class="login-form">
            <input v-model="email" type="email" placeholder="邮箱" ref="emailInput" class="input-field" />
            <input v-model="password" type="password" placeholder="密码" class="input-field" />
            <!-- 忘记了?找回密码 -->
            <div class="forgot-password" @click="goForgotpassword">忘记了?找回密码</div>
            <button v-show="showBtn" type="submit" class="submit-btn">登录</button>
          </form>
        </div>
      </div>
    </Transition>
    <!-- 注册页面  -->
    <Transition name="fade-left">
      <RegistrationPage v-if="showRegistrationPage" v-model="showRegistrationPage"></RegistrationPage>
    </Transition>
    <!-- 忘记密码页面 -->
    <Transition name="fade-left">
      <RetrievePasswordPage v-if="showgoForgotpassword" v-model="showgoForgotpassword" :email="email">
      </RetrievePasswordPage>
    </Transition>
  </Teleport>
</template>

<script setup>
import { ref, computed, defineAsyncComponent, inject } from 'vue'
import Icon from '@/components/common/Icon.vue'
import { userloginAPI } from '@/api/login'
import { getUserInfoAPI } from '@/api/user'
import { Toast } from '@/utils/showtoast'
const socket = inject('socket')
// 存储用户信息
import { useUserStore } from '@/stores/userinfo'
const userStore = useUserStore()


const model = defineModel()

// 获取当前路由信息，用于登录后重定向
import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute()

const email = ref('')
const password = ref('')

const close = () => {
  console.log(1)
  model.value = false
}

const handleSubmit = async () => {
  try {
    const res = await userloginAPI({
      email: email.value.trim(),
      password: password.value.trim()
    })

    console.log('API Response:', res)

    if (res.code === 200) {
      const { userId } = res?.data || {}
      if (!userId) {
        Toast('登录失败,用户ID不存在', { position: 'bottom' })
        return
      }

      const userInfo = await getUserInfoAPI(userId)
      console.log('用户信息:', userInfo)
      if (userInfo.code === 200) {
        userInfo.data.userAvatar = 'http://43.138.15.137:3000' + userInfo.data.userAvatar
        userStore.setUserInfo(userInfo.data)
        model.value = false
        Toast('登录成功', { position: 'bottom' })
        router.push('/')
      } else {
        Toast(userInfo.message || '获取用户信息失败', { position: 'bottom' })
      }
    } else {
      // 后端返回了错误状态，但请求成功
      Toast(res.message || '登录失败，请检查账号或密码', { position: 'bottom' })
    }
  } catch (error) {
    console.error('请求异常:', error)
    // 判断是否是网络错误 or 服务器返回非 JSON
    if (error.response && error.response.status === 400) {
      // 400 可能是业务错误，但前端没拿到 data
      Toast('密码错误，请重新输入', { position: 'bottom' })
    } else {
      Toast('网络错误，请稍后再试', { position: 'bottom' })
    }
  }
}

const showBtn = computed(() => {
  return email.value.trim() !== '' && email.value.includes('@')
})

// 组件懒加载 - 注册
const showRegistrationPage = ref(false)
const RegistrationPage = defineAsyncComponent(() => import('@/components/authentication/RegistrationPage.vue'))
// 跳转注册页
const goregister = () => {
  showRegistrationPage.value = true
}
// 忘记密码组件
const showgoForgotpassword = ref(false)
const RetrievePasswordPage = defineAsyncComponent(() => import('@/components/authentication/RetrievePasswordPage.vue'))
const goForgotpassword = () => {
  console.log(1)
  if (!email.value.trim()) {
    Toast('请输入邮箱', {
      position: 'bottom'
    })
    return;
  }
  password.value = ''
  showgoForgotpassword.value = true;
  Toast('验证码已发送,请注意查收', {
    position: 'bottom'
  })
}

</script>

<style lang="scss" scoped>
.login-modal-overlay {
  @include fixed-top;
  width: 100vw;
  height: 100vh;
  background: $white-color;
  @include flex-center;
  z-index: 10001;
}

.login-modal {
  width: 100%;
  height: 100%;
  background: white;
  border-radius: 12px;
  padding: 20px;
  position: relative;
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
  transition: all 0.3s ease;
}

.modal-header {
  @include flex-between;
  margin-bottom: 24px;

  .modal-title {
    font-size: $font-size-large;
    color: $text-color;
  }
}





.title {
  text-align: left;
  margin-bottom: 24px;
  font-size: 20px;
  color: #333;
}

.login-form {
  @include flex-center;
  flex-direction: column;

  .input-field {
    width: 100%;
  }

  .forgot-password {
    width: 100%;
    text-align: right;
    margin-bottom: 10px;
    font-size: 14px;
    cursor: pointer;
    color: $text-color;
  }
}

.input-field {
  padding: 12px 16px;
  margin-bottom: 16px;
  background: $comment-modal-input-bg-color;
  border-radius: $border-radius-md;
  font-size: $font-size-base;
  transition: border-color 0.2s;
}

.submit-btn {
  width: 100%;
  padding: 12px;
  background: #007bff;
  color: white;
  border-radius: $border-radius-md;
  font-size: $font-size-base;
  cursor: pointer;
}
</style>